//
//  AppDelegate.swift
//  xinlangweibo
//
//  Created by 陈志强 on 15/11/8.
//  Copyright © 2015年 陈志强. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
            window?.backgroundColor = UIColor.whiteColor()
            window?.makeKeyAndVisible()
            setThemColor()
        
            window?.rootViewController = defaultRootController()
        
        
        registerNotification()
        
        return true
    }

    private func setThemColor(){
        UINavigationBar.appearance().tintColor = themeColor
        UITabBar.appearance().tintColor = themeColor
    }
    
    //MARK: 判断用户是否登陆 并且是否是更新版本
    private func defaultRootController() -> UIViewController {
        if UserAccountViewModel().userLogin {
            //判断是否是新版本
            //            if isNewVersion() {
            //                return NewFeatureViewController()
            //            }
            //
            //            return WelComeViewController()
            
            return isNewVersion() ? NewFeatureViewController() : WelComeViewController()
        }
        return MainViewController()
    }
    
    //MARK: 监听通知
    private func registerNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchToRootVC:", name: AppSwitchRootViewControler, object: nil)
    }
  @objc private func switchToRootVC (n: NSNotification) {
        if ( n.object as? String ) != nil{
            window?.rootViewController = WelComeViewController()
            return
        }
        window?.rootViewController = MainViewController()
    }
    //MARK: 移除通知  编码规范而已 没有任何作用
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
     
    //MARK: 检测是否是新版本
    private func isNewVersion() -> Bool{
        
        //比较新旧版本
        //1.获取新版本
        let versionStr = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let versionNum = Double(versionStr)
        //2.获取 旧版本  一般存放在沙盒3
        
        let key = "sandBoxKey"
        let userdefaults = NSUserDefaults.standardUserDefaults()
        let lastVersion = userdefaults.doubleForKey(key)
        
        //3.保存新版本
        userdefaults.setDouble(versionNum!, forKey: key)
        //同步沙盒
        userdefaults.synchronize()
        
        //4.比较新旧版本
        return versionNum! > lastVersion
    }
}